package com.airS.task.fileMgr.utils.servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.airS.task.fileMgr.common.response.BaseResponse;
import com.airS.task.fileMgr.utils.httpConvert.CustomSerializeFilter;
import com.airS.task.fileMgr.utils.mvc.MVCShareValue;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Servlet工具类
 * Created by alan on 2017/3/14.
 */
public class ServletUtils {

    // 静态文件后缀
    private final static String[] staticFiles = StringUtils
            .split(".css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk",
                    ",");

    // 动态映射URL后缀
    private final static String urlSuffix = ".html";

    // fastjson Date日期格式
    private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    // 初始化fastjson serializeFilter
    private static final CustomSerializeFilter CUSTOM_SERIALIZE_FILTER = new CustomSerializeFilter();

    // 初始化fastjson serializerFeature
    private static final SerializerFeature[] SERIALIZER_FEATURES = new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.QuoteFieldNames};

    /**
     * 获取当前请求对象
     * @return
     */
    public static HttpServletRequest getRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断访问URI是否是静态文件请求
     * @param uri
     * @return
     */
    public static boolean isStaticFile(String uri) {
        if (staticFiles == null) {
            try {
                throw new Exception(
                        "检测到“app.properties”中没有配置“web.staticFile”属性。配置示例：\n#静态文件后缀\n"
                                + "web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.crx,.xpi,.exe,.ipa,.apk");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.endsWithAny(uri, staticFiles) && !StringUtils.endsWithAny(uri, urlSuffix)
                && !StringUtils.endsWithAny(uri, ".jsp") && !StringUtils.endsWithAny(uri, ".java")) {
            return true;
        }
        return false;
    }

    /**
     * 从mvc线程变量获取req
     * @param req
     * @return
     */
    public static HttpServletRequest getHttpRequest(ServletRequest req) {
        if (req != null)
            return (HttpServletRequest) req;
        return MVCShareValue.getRequest();
    }

    /**
     * 从mvc线程变量获取rep
     * @param rep
     * @return
     */
    public static HttpServletResponse getResponse(ServletResponse rep) {
        if (rep != null)
            return (HttpServletResponse) rep;
        return MVCShareValue.getResponse();
    }

    /**
     * 从mvc线程变量获取session
     * @param session
     * @return
     */
    public static HttpSession getSession(HttpSession session) {
        if (session != null)
            return session;
        return MVCShareValue.getSession();
    }

    public static SerializeConfig getSerializeConfig() {
        SerializeConfig sc = new SerializeConfig();
        sc.put(Date.class, new SimpleDateFormatSerializer(YYYY_MM_DD_HH_MM_SS));
        sc.put(java.sql.Date.class, new SimpleDateFormatSerializer(YYYY_MM_DD_HH_MM_SS));
        sc.put(Timestamp.class, new SimpleDateFormatSerializer(YYYY_MM_DD_HH_MM_SS));
        return sc;
    }

    /**
     * 输出json字符
     * @param obj
     * @param rep
     */
    public static void writeJson(Object obj, ServletResponse rep) {
        if (obj instanceof BaseResponse) {
            BaseResponse response = (BaseResponse) obj;
            String callback = response.getCallback();
            if (org.springframework.util.StringUtils.hasText(callback)) {
                JSONPObject jsonpObject = new JSONPObject(callback);
                jsonpObject.addParameter(response);
                obj = jsonpObject;
            }
        }
        writePlainText(JSON.toJSONString(obj, getSerializeConfig(), CUSTOM_SERIALIZE_FILTER, SERIALIZER_FEATURES), rep);
    }

    protected static void writePlainText(String text, ServletResponse rep) {
        try {
            HttpServletResponse response = getResponse(rep);
            response.setContentType("text/plain;charset=UTF-8");
            Writer writer = response.getWriter();
            writer.write(text);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
